// pages/score-page/teacher-subject-score/teacher-subject-score.js

import * as echarts from '../../../components/echarts/echarts';
const app = getApp();
const requestUtil = require("../../../utils/request");
const api = require("../../../config/api");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    params: {},
    scoreObj: {},
    examInfo: null,
    subjectArray: null,
    termList: null,
    examName: '无数据',
    teacherName: '',
    classStudentNum: 0, // 参考人数
    subjectName: '', // 科目名称
    subjectIndex: 1,
    subjectArray: [],
    navigatorSubjectArray: [],
    classExamScoreList: [], // 学期历次成绩数据
    scoreTableHeader: [],
    scoreTableList: [],
    border: true,
    tableNoDataMsg: '暂无数据~',
    subjectBarIsShow: true,
    subjectRadarIsShow: true,
    historyRadarIsShow: false,
    subjectBar: {
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const barChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(barChart);
        barChart.setOption(getBarChartOption(data));
        return barChart;
      }
    },
    radarData: {},
    subjectRateRadar: {
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const radarChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(radarChart);
        radarChart.setOption(getRateRadarOption(data));
        return radarChart;
      }
    },
    subjectStudentsRadar: {
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const radarChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(radarChart);
        radarChart.setOption(getStudentsRadarOption(data));
        return radarChart;
      }
    },
    historyRadar: {
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const radarChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(radarChart);
        radarChart.setOption(totalTermExamReport(data));
        return radarChart;
      }
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let params = {
      grade: options.grade,
      examId: options.examId,
      clazz: options.clazz,
      schoolId: options.schoolId
    }
    let subjectName = options.subjectName;

    this.getClassExamScore(params, subjectName);

    // this.getTermList();

    this.setData({
      params: params,
      subjectArray: app.globalData.subjectArray,
      subjectName,
    })

  },
  /**
   * 获取考试信息
   */
  getClassExamScore: async function (params, subjectName) {
    let that = this;
    let classExamInfo = await requestUtil.request('POST', api.getClassExamScore, params);
    let examInfo = classExamInfo.data.data.examInfo;
    let teacherScore = classExamInfo.data.data.teacherScore;
    if (teacherScore == null || !teacherScore.length > 0) {
      wx.showModal({
        title: '警告',
        content: '未找到该场考试的相关成绩，请等待教师上传成绩后再次打开。'
      })
      return;
    }
    let scoreObj = {}; // 适配页面的科目对象  
    let subjectArray = examInfo.examSubject.split(','); // 科目数组
    let examScoreRateArr = examInfo.examScoreRate.split(','); // 不知道是什么的数组
    let examFullScore = ''; // 科目满分
    let subjectEnglishName = ''; // 科目英文名
    for (let i of teacherScore) {
      if (subjectName == i.subjectName) {
        scoreObj = i;
      }
    }
    for (let j in subjectArray) {
      if (subjectName == subjectArray[j]) {
        subjectEnglishName = app.globalData.subjectEnglishNameMap().get(subjectArray[j]);
        examFullScore = examInfo.examFullScore.split(',')[j];
        scoreObj.examScoreRate = examScoreRateArr[j];
      }
    }
    let navigatorSubjectArray = [];
    // 设置跳转科目数组
    for (let e of subjectArray) {
      if (scoreObj.subjectName == e) {
        navigatorSubjectArray.push(e)
      }
    }
    navigatorSubjectArray.unshift('总分');
    that.setData({
      examInfo,
      subjectArray,
      navigatorSubjectArray,
      examName: examInfo.examName,
      scoreObj: scoreObj,
      subjectEnglishName: subjectEnglishName,
      examFullScore: examFullScore,
      radarData: {
        goodRate: scoreObj.goodRate * 100,
        lowRate: scoreObj.lowRate * 100,
        bestRate: scoreObj.bestRate * 100,
        qualifiedRate: scoreObj.qualifiedRate * 100,
        goodStudents: scoreObj.goodStudents,
        bestStudents: scoreObj.bestStudents,
        lowStudents: scoreObj.lowStudents,
        qualifiedStudents: scoreObj.qualifiedStudents,
        totalStudents: scoreObj.classStudentNum
      }
    })
    this.getTotalScore(params, subjectEnglishName, subjectName, examFullScore);
    this.getHistoryScoreData({
      grade: examInfo.grade,
      studyType: examInfo.gradeType,
      schoolId: examInfo.schoolId,
      termId: examInfo.termId
    })
  },

  /**
   * 获取学期列表（如果历次成绩分析需要不同学期的，这个就有用了）
   */
  getTermList: async function () {
    let res = await requestUtil.request('GET', api.getTermList, null);
    let termList = res.data.data;
    this.setData({
      termList,
    })
  },

  /**
   * 获取一个学期的最高分、最低分、平均分、级排名历史记录
   */
  getHistoryScoreData: async function (params) {
    // 班级考试成绩
    params.teacherId = app.globalData.teacherInfo[0].id;
    params.subjectName = this.data.subjectName;
    let res = await requestUtil.request('post', api.teacherTermExam, params);
    this.setData({
      classExamScoreList: res.data.data,
      historyRadarIsShow: true
    })
  },

  /**
   * 获取科目所有学生考试成绩
   */
  getTotalScore: async function (params, name, subjectName, examFullScore) {
    let subjectScoreKey = name + 'Score'; // 学科成绩名称
    let subjectRankKey = name + 'Rank'; // 学科成绩排名
    let scoreTableHeader = [{
      prop: 'studentName',
      width: 150,
      label: '学生姓名',
    }, {
      prop: 'sumScore',
      width: 130,
      label: '总分'
    }, {
      prop: 'examFullScore',
      width: 130,
      label: '满分'
    }, {
      prop: subjectScoreKey,
      width: 150,
      label: subjectName + '成绩'
    }, {
      prop: subjectRankKey,
      width: 150,
      label: subjectName + '排名'
    }, {
      prop: 'gradeRank',
      width: 150,
      label: '级排名'
    }, {
      prop: 'classRank',
      width: 150,
      label: '班排名'
    }, ];
    let totalScoreList = await requestUtil.request('POST', api.getClassStudentExamScore, params);
    //FIXME 数据太多了，有空研究为什么，先取前10条用
    // let virtualList = totalScoreList.data.data.slice(0, 10);
    for (let i of totalScoreList.data.data) {
      i.examFullScore = examFullScore
    }
    this.setData({
      scoreTableHeader: scoreTableHeader,
      scoreTableList: totalScoreList.data.data
    })
  },

  /**
   * 跳转科目
   */
  subjectChange: function (e) {
    // 让它切换页面的时候重置picker
    this.setData({
      subjectIndex: 1
    });
    if (e.detail.value == 0) {
      wx.navigateTo({
        url: '../teacher-view-score/teacher-view-score?grade=' + this.data.params.grade +
          '&examId=' + this.data.params.examId +
          '&clazz=' + this.data.params.clazz,
      })
    } else {
      //不跳转
      return;
    }
  },

  /**
   * 点击表格跳转到学生详情
   */
  onRowClick: function (e) {
    let rowData = e.detail.currentTarget.dataset.it; // 行数据
    let schoolId = this.data.params.schoolId;
    let grade = this.data.params.grade;
    let examId = this.data.params.examId;
    let gradeType = rowData.gradeType;
    let studentId = rowData.studentId;
    let subjectName = this.data.subjectName;
    wx.navigateTo({
      url: '../student-subject-score/score?studentId=' + studentId +
        '&schoolId=' + schoolId +
        '&gradeType=' + gradeType +
        '&grade=' + grade +
        '&examId=' + examId +
        '&subjectName=' + subjectName,
    })
  }
})

function getBarChartOption(d) {
  let arr = [
    d.scoreObj.highestScore,
    d.scoreObj.lowestScore,
    d.scoreObj.avgScore,
    d.scoreObj.gradeAvgScore
  ]
  return {
    backgroundColor: "#ffffff",
    tooltip: {
      trigger: 'axis',
      confine: true
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '3%',
      containLabel: true
    },
    // dataZoom: {
    //   type: "inside",
    //   strat: 0,
    //   end: 50,
    //   orient: "horizontal",
    // },
    xAxis: {
      type: 'category',
      data: ['最高分', '最低分', '班平均分', '级平均分'],
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      name: '分数',
      type: 'value',
    },
    series: [{
      data: arr,
      barGap: '10%',
      type: 'bar'
    }]
  };
}

function getStudentsRadarOption(d) {
  let radarData = d.radarData;
  let maxStudent = radarData.totalStudents;
  let array = [radarData.qualifiedStudents, radarData.goodStudents, radarData.bestStudents, radarData.lowStudents];
  return {
    backgroundColor: "#ffffff",
    tooltip: {
      show: true,
      trigger: 'item',
      confine: true
    },
    // xAxis: {
    //   show: false
    // },
    // yAxis: {
    //   show: false
    // },
    radar: {
      // shape: 'circle',
      indicator: [{
        name: '及格人数',
        max: maxStudent
      }, {
        name: '优秀人数',
        max: maxStudent
      }, {
        name: '特优人数',
        max: maxStudent
      }, {
        name: '不及格人数',
        max: maxStudent
      }],
      radius: 70
    },
    symbol: "circle", // 标记图形，"circle"
    series: [{
      name: '科目概况',
      type: 'radar',
      data: [{
        name: '我的分数',
        value: array,
        itemStyle: {
          color: "#fbbd08"
        }
      }],
      // label: {
      //   show: true,
      //   formatter: function (params) {
      //     return params.value;
      //   }
      // }
    }]
  };
}

function getRateRadarOption(d) {
  let radarData = d.radarData;
  let array = [radarData.qualifiedRate, radarData.goodRate, radarData.bestRate, radarData.lowRate];
  return {
    backgroundColor: "#ffffff",
    tooltip: {
      show: true,
      trigger: 'item',
      confine: true
    },
    // xAxis: {
    //   show: false
    // },
    // yAxis: {
    //   show: false
    // },
    radar: {
      // shape: 'circle',
      indicator: [{
          name: '及格率',
          max: 100
        },
        {
          name: '优秀率',
          max: 100
        },
        {
          name: '特优率',
          max: 100
        },
        {
          name: '不及格率',
          max: 100
        }
      ],
      radius: 70
    },
    symbol: "circle", // 标记图形，"circle"
    series: [{
      name: '科目概况',
      type: 'radar',
      data: [{
        name: '我的分数',
        value: array,
        itemStyle: {
          color: "#fbbd08"
        },
        // label: {
        //   show: true,
        //   formatter: function (params) {
        //     return params.value;
        //   }
        // }
      }, ]
    }]
  };
}

function totalTermExamReport(d) {
  let list = d.classExamScoreList;
  var examMap = new Map(),
    classMap = new Map(),
    seriesData = [];
  for (var i in list) {
    if (!classMap.has(list[i].classGrade)) {
      classMap.set(list[i].classGrade, list[i].classGrade + "班");
      seriesData.push({
        'name': list[i].classGrade + "班",
        data: []
      })
    }
    if (!examMap.has(list[i].examName)) {
      examMap.set(list[i].examName, list[i].examName);
    }
    for (var k in seriesData) {
      if (seriesData[k]["name"] == (list[i].classGrade + "班")) {
        seriesData[k]["data"].push(list[i].strengthRank);
        break;
      }
    }
  }
  return {
    title: {
      text: ''
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      hoverable: true,
      top: 50,
      bottom: '40%',
      left: '15%',
      width: '70%',
    },
    legend: {
      data: (function () {
        var arry = [];
        for (let i of classMap.values()) {
          arry.push(i);
        }
        return arry;
      }())
    },
    xAxis: {
      type: 'category',
      name: "考试",
      boundaryGap: false,
      axisLabel: {
        interval: 0,
        rotate: 82
      },
      data: (function () {
        var arry = [];
        for (let i of examMap.values()) {
          arry.push(i);
        }
        return arry;
      }())
    },
    yAxis: {
      type: 'value',
      name: "排名",
      inverse: true,
      min: 1,
      nameLocation: 'start'
    },
    series: (function () {
      var list = [];
      for (var i in seriesData) {
        list.push({
          name: seriesData[i].name,
          type: 'line',
          data: seriesData[i].data,
          markPoint: {
            symbolSize: 30,
            data: [{
                type: 'max',
                name: '最高'
              },
              {
                type: 'min',
                name: '最低'
              }
            ]
          }
        })
      }
      return list;
    }())
  }
}